package com.ld.zxw.core;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.ld.zxw.config.LuceneDataSource;

import redis.clients.jedis.Jedis;


public class CoreFilter implements Filter{
	
	
	public static Jedis jedis;
	
	/**
	 * 初始化加载
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		createJFinalConfig(filterConfig.getInitParameter("configClass"));
		jedis = new Jedis(LuceneDataSource.redis_host,LuceneDataSource.redis_prot);
		if(LuceneDataSource.redis_pwd != null){
			jedis.auth(LuceneDataSource.redis_pwd);
		}
	}

	/**
	 * 请求过滤
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		request.setAttribute("contextPath", request.getServletContext().getContextPath());
		chain.doFilter(request, response);
	}

	/**
	 * 销毁
	 */
	@Override
	public void destroy() {
		jedis.close();
	}
	
	private void createJFinalConfig(String configClass) {
		if (configClass == null) {
			throw new RuntimeException("Please set configClass parameter of JFinalFilter in web.xml");
		}
		
		Object temp = null;
		try {
			temp = Class.forName(configClass).newInstance();
		} catch (Exception e) {
			throw new RuntimeException("Can not create instance of class: " + configClass, e);
		}
		
		if (temp instanceof LDConfig) {
			LDConfig ldConfig = (LDConfig)temp;
			ldConfig.basicsConfig();
		} else {
			throw new RuntimeException("Can not create instance of class: " + configClass + ". Please check the config in web.xml");
		}
	}
	
	/**
	 * 手动启动
	 * @param classUrl
	 */
	public void manualStart(String classUrl){
		createJFinalConfig(classUrl);
		jedis = new Jedis(LuceneDataSource.redis_host,LuceneDataSource.redis_prot);
		if(LuceneDataSource.redis_pwd != null){
			jedis.auth(LuceneDataSource.redis_pwd);
		}
	}
}
